package com.puman.beautyfarmcounselor.ui.customer;

import android.app.AlertDialog;
import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.puman.beautyfarmcounselor.IndexActivity;
import com.puman.beautyfarmcounselor.MainActivity;
import com.puman.beautyfarmcounselor.R;
import com.puman.beautyfarmcounselor.http.AjaxCallBack;
import com.puman.beautyfarmcounselor.ui.core.BaseFragment;
import com.puman.beautyfarmcounselor.ui.core.BaseInferface;
import com.puman.beautyfarmcounselor.ui.customer.ui.MyScrollView;
import com.puman.beautyfarmcounselor.ui.home.model.CustomerDetail;
import com.puman.beautyfarmcounselor.util.MethedUtil;
import com.puman.beautyfarmcounselor.util.XTHttp;
import com.puman.beautyfarmcounselor.util.config.RequestAddr;
import com.puman.beautyfarmcounselor.util.view.XCFlowLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.ViewsById;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 *
 */
@EFragment(R.layout.fragment_customer_detail)
public class CustomerDetailFragment extends BaseFragment implements BaseInferface {


    /**
     * init UI
     */
    @ViewById(R.id.back_btn)
    ImageView backBtn;
    @ViewById(R.id.base_title)
    TextView title;
    @ViewById(R.id.customer_detail_top)
    View mHeader;
    //    @ViewById(R.id.image)
//    ImageView mTopImage;
    @ViewById(R.id.scrollView)
    MyScrollView scrollViews;
    @ViewById(R.id.detail_customer_info_layout)
    RelativeLayout detailLayout;

    @ViewById(R.id.flowlayout)
    XCFlowLayout mFlowLayout;
    private int mMinHeaderTranslation;
    private int mMinHeaderHeight;

    @ViewById(R.id.detail_tel_icon)
    ImageView telImg;
    @ViewById(R.id.detail_msg_icon)
    ImageView msgImg;




    @ViewsById({R.id.detail_customer_info, R.id.detail_tel, R.id.detail_wechart, R.id.detail_brithday, R.id.detail_store,
            R.id.detail_consume_record_content, R.id.detail_consume_lasttime_content,
            R.id.detail_back_record_content, R.id.detail_back_lasttime_content,
            R.id.detail_surplus_record_content, R.id.detail_surplus_lasttime_content})
    List<TextView> detailList;

    @FragmentArg
    int customerId;
    @FragmentArg
    boolean feedbackTel;
    @FragmentArg
    boolean feedbackMsg;

    @FragmentArg
    String msgContent;//短信模板

    @Override
    @AfterViews
    public void updateView() {
        mMinHeaderHeight = getResources().getDimensionPixelSize(R.dimen.min_header_height);
        mMinHeaderTranslation = -mMinHeaderHeight;
        mHeader.setTranslationY(0);
        detailLayout.setTranslationY(0);

        title.setText(R.string.detailTitle);
        backBtn.setVisibility(View.VISIBLE);
        scrollViews.setOnScrollChangedListener(new MyScrollView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(ScrollView view, int l, int t, int oldl, int oldt) {
                onScrollViewScroll(view, l, t, oldl, oldt);
            }
        });

        if (feedbackTel){
            telImg.setVisibility(View.VISIBLE);
        }else{
            telImg.setVisibility(View.GONE);
        }
        if (feedbackMsg){
            msgImg.setVisibility(View.VISIBLE);
        }else{
            msgImg.setVisibility(View.GONE);
        }

        getData();
    }


    XTHttp xtHttp = new XTHttp();
    String url = "";
    String param = "";

    private void getData() {
        param = "customer_id=" + customerId;
        url = RequestAddr.detail + param;
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
//                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    CustomerDetail customerDetail;

    private void dealData(Object o) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            customerDetail = mapper.readValue(o.toString(), CustomerDetail.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (customerDetail == null)
            return;


        detailList.get(0).setText(customerDetail.getData().getChinese_name() + " " + customerDetail.getData().getGender() + " " + customerDetail.getData().getCity());
        detailList.get(1).setText(customerDetail.getData().getMobile());
        detailList.get(2).setText(customerDetail.getData().getWechat());
        detailList.get(3).setText(customerDetail.getData().getBirthday());
        detailList.get(4).setText(customerDetail.getData().getStore_name());
        detailList.get(5).setText(customerDetail.getData().getConsumer_count() + "");
        detailList.get(6).setText(customerDetail.getData().getLast_order());
        detailList.get(7).setText(customerDetail.getData().getVisit_count() + "");
        detailList.get(8).setText(customerDetail.getData().getLast_visit());
        detailList.get(9).setText(customerDetail.getData().getSurplus_list_size() + "");
        detailList.get(10).setText(customerDetail.getData().getLast_end_date());

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.leftMargin=10;
        layoutParams.rightMargin=10;
        layoutParams.topMargin =5;
        layoutParams.bottomMargin = 5;
        lables = customerDetail.getData().getLabels().split(",");
//        lables = customerDetail.getData().getLabels().split(",");
        Arrays.toString(lables);
        MethedUtil.UtilLog("lables:" + Arrays.toString(lables));
        lableList =  customerDetail.getData().getLabels();
        for(int i = 0; i < lables.length; i ++){
            TextView view = new TextView(MainActivity.getInstace());
            view.setText(lables[i]);
            view.setTextColor(getActivity().getResources().getColor(R.color.themeColor));
            view.setBackground(getActivity().getResources().getDrawable(R.drawable.circle_white_bg_gray_bound));
            mFlowLayout.addView(view,layoutParams);
        }
        mFlowLayout.setLayoutParams(layoutParams);

    }

    String[] lables;
    String lableList;

    public void onScrollViewScroll(ScrollView view, int x, int y, int oldX, int oldY) {
        scrollHeader(view.getScrollY());
    }

    private void scrollHeader(int scrollY) {
        float translationY = Math.max(-scrollY, mMinHeaderTranslation);
        mHeader.setTranslationY(translationY);
//        mTopImage.setTranslationY(-translationY / 2);
        detailLayout.setTranslationY(-translationY / 3);
    }

    @Override
    @Click({R.id.back_btn, R.id.detail_consumeRecord_layout, R.id.detail_BackRecord_layout, R.id.detail_surplus_layout, R.id.detail_tel_icon, R.id.detail_lable_layout, R.id.detail_msg_icon})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                MainActivity.getInstace().getSupportFragmentManager().popBackStack();
                break;
            case R.id.detail_consumeRecord_layout:
//                MainActivity.getInstace().switchFragment(this, new ConsumeFragment_());
                MainActivity.getInstace().getSupportFragmentManager()
                        .beginTransaction()
                        .hide(this)
                        .replace(R.id.content_none_bottom, ConsumeFragment_.builder()
                                .customerId(customerId)
                                .build())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.detail_BackRecord_layout:
                MainActivity.getInstace().getSupportFragmentManager()
                        .beginTransaction()
                        .hide(this)
                        .replace(R.id.content_none_bottom, BackRecordFragment_.builder()
                                .customerId(customerId)
                                .build())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.detail_surplus_layout:
                MainActivity.getInstace().getSupportFragmentManager()
                        .beginTransaction()
                        .hide(this)
                        .replace(R.id.content_none_bottom, SurplusFragment_.builder()
                                .customerId(customerId)
                                .build())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.detail_tel_icon:
//                Intent intent = new Intent(Intent.ACTION_CALL, // 创建一个意图
//                        Uri.parse("tel:"
//                                + customerDetail.getData().getMobile()));
//                MainActivity.getInstace().startActivity(intent);// 开始意图(及拨打电话)
                showNoticy(1);
                break;
            case R.id.detail_msg_icon:
                showNoticy(2);
                break;
            case R.id.detail_lable_layout:
                MainActivity.getInstace().getSupportFragmentManager()
                        .beginTransaction()
                        .hide(this)
                        .replace(R.id.content_none_bottom, CusLableFragment_.builder()
                                .lableList(lableList)
                                .customer_id(customerId)
                                .build())
                        .addToBackStack(null)
                        .commit();
                break;

        }
    }

    private AlertDialog alertDialog;
    private void showNoticy(final int showFlag) {
        alertDialog = new AlertDialog.Builder(MainActivity.getInstace()).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.info_dialog);
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);// 弹出键盘
        TextView info = (TextView) window.findViewById(R.id.call_state);
        if (showFlag == 1){
            MethedUtil.UtilLog("showFlag:"+showFlag);
            info.setText(R.string.call_info);
        }else{
            MethedUtil.UtilLog("showFlag:"+showFlag);
            info.setText(R.string.send_msg_info);
        }
        RelativeLayout sureBtn = (RelativeLayout) window.findViewById(R.id.sure_btn_layout);
        RelativeLayout cloWin = (RelativeLayout) window.findViewById(R.id.close_win);

        sureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                if (showFlag == 1) {
                    Intent intent = new Intent(Intent.ACTION_CALL, // 创建一个意图
                            Uri.parse("tel:"
                                    + customerDetail.getData().getMobile()));
                    MainActivity.getInstace().startActivity(intent);// 开始意图(及拨打电话)
                } else {
                    String phone_number = detailList.get(1).getText().toString().trim();
                    String sms_content = msgContent;
                    Uri uri = Uri.parse("smsto:" + phone_number);
                    Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
                    sendIntent.putExtra("sms_body", sms_content);
                    MainActivity.getInstace().startActivity(sendIntent);
                }

            }
        });

        cloWin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

}
